package channels

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
)

type SlackConfig struct {
	WebhookURL string
	BotToken   string
}

type SlackChannel struct {
	config SlackConfig
}

func NewSlackChannel(config SlackConfig) *SlackChannel {
	return &SlackChannel{config: config}
}

type SlackMessage struct {
	Channel     string            `json:"channel,omitempty"`
	Text        string            `json:"text"`
	Attachments []SlackAttachment `json:"attachments,omitempty"`
}

type SlackAttachment struct {
	Color      string `json:"color,omitempty"`
	Title      string `json:"title,omitempty"`
	Text       string `json:"text,omitempty"`
	Footer     string `json:"footer,omitempty"`
	FooterIcon string `json:"footer_icon,omitempty"`
}

func (s *SlackChannel) Send(recipients []string, subject, body string) error {
	// Build Slack message
	msg := SlackMessage{
		Text: fmt.Sprintf("*%s*", subject),
		Attachments: []SlackAttachment{
			{
				Color: s.getColorBySubject(subject),
				Text:  body,
				Footer: "DevOps SmartBot",
			},
		},
	}

	// If recipients specified (channel names), send to first recipient
	if len(recipients) > 0 {
		msg.Channel = recipients[0]
	}

	// Convert to JSON
	jsonData, err := json.Marshal(msg)
	if err != nil {
		return fmt.Errorf("failed to marshal slack message: %w", err)
	}

	// Send to Slack webhook
	resp, err := http.Post(s.config.WebhookURL, "application/json", bytes.NewBuffer(jsonData))
	if err != nil {
		return fmt.Errorf("failed to send slack message: %w", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("slack API returned status %d", resp.StatusCode)
	}

	return nil
}

func (s *SlackChannel) getColorBySubject(subject string) string {
	// Determine color based on subject keywords
	subjectLower := subject
	if contains(subjectLower, "critical") || contains(subjectLower, "down") {
		return "danger" // Red
	} else if contains(subjectLower, "warning") {
		return "warning" // Yellow
	} else if contains(subjectLower, "resolved") || contains(subjectLower, "completed") {
		return "good" // Green
	}
	return "#667eea" // Default purple
}

func contains(s, substr string) bool {
	return len(s) >= len(substr) && s[:len(substr)] == substr
}

func (s *SlackChannel) Name() string {
	return "slack"
}
